package com.lyf.core.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import com.lyf.core.pojo.Department;

@Repository
public interface DepartmentDao {


	@Insert("insert into ma_department(p_id,create_uid,department_name,leader_name,leader_tel,description)"
			+ " values(#{d.p_id},#{d.create_uid},#{d.department_name},#{d.leader_name},#{d.leader_tel},#{d.description})")
	@Options(useGeneratedKeys=true , keyColumn="did" , keyProperty="d.did")
	public void insert(@Param("d") Department depart);
	
	/**
	 * 删除的同时需要清理相关子部门并且顺带更新了用户表中从属于该部门的用户DID为空
	 * @param did
	 */
	@Delete(  " delete  from   ma_department   where  did = #{did}")
	public void delete(@Param("did")  int did);

	@Update("update ma_department set department_name=#{d.department_name} , leader_name=#{d.leader_name} ,"
			+ " leader_tel = #{d.leader_tel},description=#{d.description},last_modify_time=#{d.last_modify_time} "
			+ " where did=#{d.did}")
	public void update(@Param("d") Department depart);
	
	@Select("select t1.* , case (select 1 from ma_department as t2 where t1.did = t2.p_id limit 1) when 1 then 'closed' else 'open' end as state from ma_department as t1 where t1.did = #{did} ")
	public Department selectById(@Param("did") int did);
	
	/**
	 * 按照上级部门ID和名称查找部门-为了判断同级别下不能重名
	 * @param pid 上级部门ID
	 * @param dept_name 部门名称
	 * @return
	 */
	@Select("select did from ma_department where p_id = #{pid} and department_name=#{dept_name}")
	public Department selectPidAndDeptName(@Param("pid")int pid ,@Param("dept_name") String dept_name);
	
	@Select("select * from ma_department")
	public List<Department> findAll();
	
	/**
	 * 查找当前部门下的隶属部门
	 * @param pid 父节点ID
	 * @return
	 */
	@Select("select t1.* , case (select 1 from ma_department as t2 where t1.did = t2.p_id limit 1) when 1 then 'closed' else 'open' end as state ,"
			+ " (select department_name from ma_department as t3 where t3.did = t1.p_id) as parent_name "
			+ "from ma_department as t1 where t1.p_id = #{pid}   ")
	public List<Department> findByPid(  @Param("pid")int pid);
	
 
}
